package com.wanxi.util;

import java.sql.*;


/**
     * JDBC的书写步骤
     * 1.加载驱动  整个项目只加载一次
     * 2.得到数据库的连接
     * 3.编译sql语句
     * 4.执行sql语句
     * 5.返回结果
     * 6.关闭连接
     */
/**
 * @author 杨金乾
 */
    public class JDBC {
        static {
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        private static final String URL ="jdbc:mysql://127.0.0.1:3306/fuzhuang?serverTimezone=UTC&characterEncoding=UTF-8";
        private static final String USER = "root";
        private static final String PASSWORD = "123456";
        private static PreparedStatement preparedStatement = null;

        private static Connection getConnection() {
            Connection conn = null;
            try {
                conn = DriverManager.getConnection(URL, USER, PASSWORD);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return conn;
        }


        /**
         * 无论增加修改删除都是sql语句不一样，则直接传递一个sql语句即可
         *
         * @param
         * @return
         */
        public static int update(String sql) {
            try {
//            编译sql
                preparedStatement = getConnection().prepareStatement(sql);
//            执行sql
                int rows = preparedStatement.executeUpdate();
                return rows;
            } catch (SQLException e) {
                e.printStackTrace();
                return -1;
            }

        }

        public static ResultSet query(String sql) {
            try {
//            编译sql
                preparedStatement = getConnection().prepareStatement(sql);
//            执行sql

                return preparedStatement.executeQuery();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return null;
        }

    public static int count(String sql) {
        ResultSet query = JDBC.query(sql);
        try {
            while (query.next()) {
                return query.getInt("count");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
